package com.me.components.map {
	import flash.events.Event;
	import flash.events.MouseEvent;

	import mx.core.FlexGlobals;
	import mx.core.mx_internal;
	import mx.events.MoveEvent;

	import spark.core.SpriteVisualElement;

	/**
	 *
	 * @author yw
	 *
	 * @Date 2011-9-16 下午04:24:47
	 */
	public class GridLayer extends SpriteVisualElement {

		private var _gridSize:int = 32;

		private var _gridStatus:Array = [];

		private var _cols:int = 0;

		private var _rows:int = 0;

		public function GridLayer(w:int, h:int) {
			super();
			width = w;
			height = h;
			_rows = height / _gridSize;
			_cols = width / _gridSize;
			for (var row:int = 0; row < _rows; row++) {
				var detail:Array = [];
				for (var col:int = 0; col < _cols; col++) {
					detail.push(1);
				}
				_gridStatus.push(detail);
			}
			drawGrid();
			addEventListener(MouseEvent.CLICK, drawMaskHandler);
			addEventListener(MouseEvent.MOUSE_MOVE, moveMoveHandler);
		}

		private function moveMoveHandler(e:MouseEvent):void {
			var clickcol:int = int(e.localX / _gridSize);
			var clickrow:int = int(e.localY / _gridSize);
			FlexGlobals.topLevelApplication.status = "X:" + e.localX + ".Y:" + e.localY + "/行:" + clickrow + ".列:" + clickcol;
		}

		private function drawMaskHandler(e:MouseEvent):void {
			var clickcol:int = int(e.localX / _gridSize);
			var clickrow:int = int(e.localY / _gridSize);

			if (clickrow >= _gridStatus.length || clickcol >= _gridStatus[0].length) {
				return;
			}

			_gridStatus[clickrow][clickcol] = _gridStatus[clickrow][clickcol] == 0 ? 1 : 0;

			drawGrid();
		}

		private function drawGrid():void {
			var hLines:int = height / _gridSize;
			var wLines:int = width / _gridSize;

			graphics.clear();

			graphics.beginFill(0xFF0000, .0);
			graphics.drawRect(0, 0, width, height);
			graphics.endFill();

			graphics.beginFill(0xFF0000, 1.0);

			for (var w:int = 1; w < wLines; w++) {
				graphics.moveTo(w * _gridSize, 0);
				graphics.lineStyle(1, 0xFF0000, 1);
				graphics.lineTo(w * _gridSize, height);
			}

			for (var h:int = 1; h < hLines; h++) {
				graphics.moveTo(0, h * _gridSize);
				graphics.lineStyle(1, 0xFF0000, 1);
				graphics.lineTo(width, h * _gridSize);
			}

			graphics.endFill();

			graphics.beginFill(0xFF0000, 0.4);

			for (var row:int = 0; row < _gridStatus.length; row++) {
				for (var col:int = 0; col < _gridStatus[row].length; col++) {
					if (!_gridStatus[row][col]) {
						graphics.drawRect(col * _gridSize, row * _gridSize, _gridSize, _gridSize);
					}
				}
			}

			graphics.endFill();
		}

		public function clear():void {
			graphics.clear();
		}

		public function get gridSize():int {
			return _gridSize;
		}

		public function get gridStatus():Array {
			return _gridStatus;
		}

		public function get cols():int {
			return _cols;
		}

		public function get rows():int {
			return _rows;
		}
	}
}